package com.ruoyi.project.system.order.refuse.controller;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.WeixinUtils;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.coin.domain.Coin;
import com.ruoyi.project.system.coin.dto.CoinDto;
import com.ruoyi.project.system.coin.service.ICoinService;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.order.order.domain.OrderOrder;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.order.service.IOrderOrderService;
import com.ruoyi.project.system.order.refuse.domain.OrderRefuse;
import com.ruoyi.project.system.order.refuse.dto.RefuseDto;
import com.ruoyi.project.system.order.refuse.service.IOrderRefuseService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * 退款单Controller
 * 
 * @author LCL
 * @date 2020-06-29
 */
@Controller
@RequestMapping("/system/refuse")
public class OrderRefuseController extends BaseController
{
    private String prefix = "system/refuse";

    @Autowired
    private IOrderRefuseService orderRefuseService;

    @Resource
    private IdGererateFactory idGererateFactory;

    @Resource
    private IOrderOrderService orderOrderService;

    @Resource
    private IMemberService memberService;

    @Resource
    private ICoinService coinService;

    @RequiresPermissions("system:refuse:view")
    @GetMapping()
    public String refuse()
    {
        return prefix + "/refuse";
    }

    @RequiresPermissions("system:refuse:view")
    @GetMapping("/refuse1")
    public String refuse1()
    {
        return prefix + "/refuse2";
    }

    /**
     * 查询退款单列表
     */
    @RequiresPermissions("system:refuse:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(OrderRefuse orderRefuse)
    {
        startPage();
        List<RefuseDto> list = orderRefuseService.selectOrderRefuseList(orderRefuse);
        return getDataTable(list);
    }

    /**
     * 导出退款单列表
     */
//    @RequiresPermissions("system:refuse:export")
//    @Log(title = "退款单", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    @ResponseBody
//    public AjaxResult export(OrderRefuse orderRefuse)
//    {
//        List<OrderRefuse> list = orderRefuseService.selectOrderRefuseList(orderRefuse);
//        ExcelUtil<OrderRefuse> util = new ExcelUtil<OrderRefuse>(OrderRefuse.class);
//        return util.exportExcel(list, "refuse");
//    }

    /**
     * 新增退款单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存退款单
     */
    @RequiresPermissions("system:refuse:add")
    @Log(title = "退款单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(OrderRefuse orderRefuse)
    {
        return toAjax(orderRefuseService.insertOrderRefuse(orderRefuse));
    }

    /**
     * 修改退款单
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        OrderRefuse orderRefuse = orderRefuseService.selectOrderRefuseById(id);
        mmap.put("orderRefuse", orderRefuse);
        return prefix + "/edit";
    }

    /**
     * 修改保存退款单
     */
    @RequiresPermissions("system:refuse:edit")
    @Log(title = "退款单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(OrderRefuse orderRefuse)
    {
        return toAjax(orderRefuseService.updateOrderRefuse(orderRefuse));
    }

    /**
     * 删除退款单
     */
    @RequiresPermissions("system:refuse:remove")
    @Log(title = "退款单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(orderRefuseService.deleteOrderRefuseByIds(ids));
    }


    @PostMapping("/agree/{id}")
    @Transactional
    @ResponseBody
    public AjaxResult agree(@PathVariable String id,@RequestParam String consigneeName,@RequestParam String consigneeTel,@RequestParam String address){
        OrderRefuse oldRefuse = this.orderRefuseService.selectOrderRefuseById(id);
        if(oldRefuse==null){
            return AjaxResult.error();
        }
        OrderRefuse orderRefuse = new OrderRefuse();
        orderRefuse.setId(id);
        if(oldRefuse.getType()==1){
            orderRefuse.setStatus(2);
            orderRefuse.setConsigneeName(consigneeName);
            orderRefuse.setConsigneeTel(consigneeTel);
            orderRefuse.setAddress(address);
        }else{
            orderRefuse.setStatus(2);
            orderRefuse.setConsigneeName(consigneeName);
            orderRefuse.setConsigneeTel(consigneeTel);
            orderRefuse.setAddress(address);
//            orderRefuse.setRefundNo(this.idGererateFactory.nextId().toString());
//            OrderOrder update = new OrderOrder();
//            update.setId(orderRefuse.getOrderId());
//            update.setStatus(OrderStatus.RETUREN_SUCCESS.getValue());
//            this.orderOrderService.updateOrderOrder(update);
        }
        this.orderRefuseService.updateOrderRefuse(orderRefuse);

        // 取消返利
        OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(oldRefuse.getOrderId());//得到订单信息
        Coin coin = new Coin();
        coin.setResId(orderOrder.getOrderNo());
        List<CoinDto> coinDtoList = this.coinService.selectHaoqiCoinRecordList(coin);//得到返利记录

        if (coinDtoList.size()>0) {
            for (Coin coinr:coinDtoList) {
                // 状态变为拒绝
                Coin byResId = this.coinService.selectHaoqiCoinRecordById(coinr.getId());
                Coin coin1 = new Coin();
                coin1.setId(byResId.getId());
                coin1.setStatus(2);
                this.coinService.updateHaoqiCoinRecord(coin1);
            }
        }
//        for (Coin coinr:coinDtoList) {
//            Member memberById = this.memberService.selectMemberById(coinr.getMemberId());//得到用户信息
//            Member member = new Member();
//            member.setId(memberById.getId());
//            member.setCoin(memberById.getCoin().subtract(coinr.getNum()));
//            this.memberService.updateMember(member);
//        }


//
//        SortedMap<String, Object> date = new TreeMap<String,Object>();
//        date.put("appid",AppBeanInjector.weixinConfig.getAppId());
//        date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
//        date.put("nonce_str",this.idGererateFactory.nextStringId());
//        date.put("out_refund_no",orderRefuse.getRefundNo());
//        date.put("out_trade_no",orderRefuse.getRefundNo()+"-"+this.idGererateFactory.nextStringId());
//        float sessionmoney = Float.parseFloat(orderOrder.getPriceRealPay().toString());
//        String finalmoney = String.format("%.2f", sessionmoney);
//        finalmoney = finalmoney.replace(".", "");
//        String newStr = finalmoney.replaceFirst("^0*", "");
//        date.put("refund_fee",newStr);
//        float sessionmoney1 = Float.parseFloat(oldRefuse.getPrice().toString());
//        String finalmoney1 = String.format("%.2f", sessionmoney1);
//        finalmoney1 = finalmoney1.replace(".", "");
//        String newStr1 = finalmoney1.replaceFirst("^0*", "");
//        date.put("total_fee",newStr1);
//        date.put("notify_url",AppBeanInjector.weixinConfig.getRefuse_notify_url());
//        WeixinUtils.getRefuse(date);
        return AjaxResult.success();
    }

    @PostMapping("/refuse/{id}")
    @Transactional
    @ResponseBody
    public AjaxResult refuse(@PathVariable String id){
//        OrderRefuse orderRefuse = new OrderRefuse();
//        orderRefuse.setId(id);
//        orderRefuse.setStatus(4);
//        this.orderRefuseService.updateOrderRefuse(orderRefuse);
        OrderRefuse oldData = this.orderRefuseService.selectOrderRefuseById(id);
        //修改订单状态为已完成 并且取消售后状态
        OrderOrder order = new OrderOrder();
        order.setId(oldData.getOrderId());
        order.setStatus(OrderStatus.COMPLETE.getValue());
        order.setIsRefund(0);
        this.orderOrderService.updateOrderOrder(order);
        //拒绝以后修改申请售后单为拒绝
        OrderRefuse orderRefuse = new OrderRefuse();
        orderRefuse.setId(id);
        orderRefuse.setStatus(5);
        this.orderRefuseService.updateOrderRefuse(orderRefuse);
        return AjaxResult.success();
    }

    @PostMapping("/result")
    @ResponseBody
    public Object weixinResult(HttpServletRequest req, HttpServletResponse res){
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~退款成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
            SortedMap<String ,String > sortedMap = new TreeMap();
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                String refuseNo = mapFromXml.get("out_trade_no").toString().split("-")[0];
                OrderRefuse orderRefuse = this.orderRefuseService.findByNo(refuseNo);
                if (orderRefuse==null){
                    sortedMap.put("return_code","FAIL");
                    sortedMap.put("return_msg","签名失败");
                    res.reset();
                    res.getWriter().write(parseXML(sortedMap));
                }
                if (orderRefuse.getStatus()!=1){
                    return "fail";
                }
                //  验签成功后
                orderRefuse.setStatus(2);
                this.orderRefuseService.updateOrderRefuse(orderRefuse);
                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");
                res.reset();
                res.getWriter().write(parseXML(sortedMap));

            }else {
                sortedMap.put("return_code","FAIL");
                sortedMap.put("return_msg","签名失败");
                res.reset();
                res.getWriter().write(parseXML(sortedMap));
            }
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }


    //输出XML
    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }


    @PostMapping("/agree1/{id}")
    @Transactional
    @ResponseBody
    public AjaxResult agree1(@PathVariable String id){
        OrderRefuse oldRefuse = this.orderRefuseService.selectOrderRefuseById(id);
        if(oldRefuse==null){
            return AjaxResult.error();
        }
        OrderRefuse orderRefuse = new OrderRefuse();
        orderRefuse.setId(id);
        if(oldRefuse.getType()==1){
            orderRefuse.setStatus(4);
        }else{
            orderRefuse.setStatus(4);
            orderRefuse.setRefundNo(this.idGererateFactory.nextId().toString());
        }
        orderRefuse.setRefundTime(DateUtils.getNowDate());
        this.orderRefuseService.updateOrderRefuse(orderRefuse);
        OrderOrder update = new OrderOrder();
        update.setId(orderRefuse.getOrderId());
        update.setStatus(OrderStatus.RETUREN_SUCCESS.getValue());
        this.orderOrderService.updateOrderOrder(update);
//        OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(oldRefuse.getOrderId());


//
//        SortedMap<String, Object> date = new TreeMap<String,Object>();
//        date.put("appid",AppBeanInjector.weixinConfig.getAppId());
//        date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
//        date.put("nonce_str",this.idGererateFactory.nextStringId());
//        date.put("out_refund_no",orderRefuse.getRefundNo());
//        date.put("out_trade_no",orderRefuse.getRefundNo()+"-"+this.idGererateFactory.nextStringId());
//        float sessionmoney = Float.parseFloat(orderOrder.getPriceRealPay().toString());
//        String finalmoney = String.format("%.2f", sessionmoney);
//        finalmoney = finalmoney.replace(".", "");
//        String newStr = finalmoney.replaceFirst("^0*", "");
//        date.put("refund_fee",newStr);
//        float sessionmoney1 = Float.parseFloat(oldRefuse.getPrice().toString());
//        String finalmoney1 = String.format("%.2f", sessionmoney1);
//        finalmoney1 = finalmoney1.replace(".", "");
//        String newStr1 = finalmoney1.replaceFirst("^0*", "");
//        date.put("total_fee",newStr1);
//        date.put("notify_url",AppBeanInjector.weixinConfig.getRefuse_notify_url());
//        WeixinUtils.getRefuse(date);
        return AjaxResult.success();
    }

}
